package com.yx1996.bean.day02.proxy;

import com.yx1996.bean.day02.service.UserService;
import com.yx1996.bean.day02.service.UserServiceImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


/**
 * 动态代理
 */
public class UserServiceProxyFactory implements InvocationHandler {

    private UserService us;


    //生成动态代理的新对象Proxy.newProxyInstance（当前类的类加载器，代理类实现的接口，实现InvocationHandler
    //              接口（该接口实现增强方法）的类）  返回一个增强的对象
    public UserService getUserService(){
        //生成动态代理
        UserService usProxy = (UserService) Proxy.newProxyInstance(UserServiceProxyFactory.class.getClassLoader(),
                UserServiceImpl.class.getInterfaces(), this);

        return usProxy;
    }




    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("打开事务");
        Object invoke = method.invoke(us, args);
        System.out.println("关闭事务");
        return invoke;
    }

    public UserServiceProxyFactory(UserService us) {
        this.us = us;
    }
}
